﻿using System.Collections.Generic;
using Microsoft.Xna.Framework;
using RaptorEngine.Components;
using RaptorEngine.Components.CollidableComponent;

namespace RaptorEngine.Managers
{
	/// <summary>
	/// Applys the physicsRules and handles the movement of entitys based on the entity's velocity and acceleration.
	/// </summary>
	public class PhysicsManager
	{
        //The gravity applied to every movable component each update
        private Vector3 _gravity = new Vector3(0, -.001f, 0);
        public Vector3 Gravity { get { return _gravity; } set { _gravity = value; } }

	    public void Update(GameTime gt, Scene scene)
		{
			List<Movable> movables = scene.GetMoveableComponents();
			foreach (var movable in movables)
			{
				movable.Update(gt);
			}
			UpdateBoundingBoxes(movables);
			CheckCollisions(scene, gt);
		}

		private void UpdateBoundingBoxes(List<Movable> movables)
		{
			foreach (Movable movable in movables)
			{
				if (movable.Entity.HasComponent(ComponentType.Collidable))
				{
					Collidable col = (Collidable) movable.Entity.GetComponent(ComponentType.Collidable);
					col.UpdateBoundingVolumes();
				}
			}
		}

        private void CheckCollisions(Scene scene, GameTime gameTime)
		{
			List<Collidable> collidables = scene.GetCollidableComponents();
			
			foreach (Collidable col in collidables)
			{
				foreach (BoundingVolume vol in col.BoundingVolumes.Values)
				{
					vol.IsCalculated = false;
				}
			}

			for (int i = 0; i < collidables.Count; i++)
			{
				for (int j = i+1; j < collidables.Count; j++)
				{
                    collidables[i].CheckCollision(collidables[j], gameTime);
				}
			}
		}
	}
}
